﻿// //  ********************************************************************************
// //  Copyright (C) 2016 Sebastian Kenter. All rights reserved.
// // 
// //  Name    : MultiServerEngine | ServerFramework | ServerPeerRegistry.cs
// //  Created : 2016 - 02 - 16 20:53
// //  Modified: 2016 - 02 - 20 12:33
// //  ********************************************************************************

using System.Collections.Generic;
using System.Linq;
using ExitGames.Logging;
using ServerFramework.Interfaces.Server;
using TypeDefs;

namespace ServerFramework.Implementation.Server
{
    /// <summary>
    ///     Instance of the ServerPeerRegistry.
    /// </summary>
    public class ServerPeerRegistry : IServerPeerRegistry<IServerPeer>
    {
        public ILogger Logger { get; }

        private readonly Dictionary<ServerTypes, IServerPeer> _serverPeers;

        public ServerPeerRegistry(ILogger logger)
        {
            Logger = logger;
            _serverPeers = new Dictionary<ServerTypes, IServerPeer>();
        }

        public bool RegisterPeer(ServerTypes peerType, IServerPeer serverPeer)
        {
            Logger.DebugFormat("Received register server peer request for server={0} on server={1}", peerType,
                serverPeer.ServerType);

            // Did we already register the server peer?
            if (_serverPeers.ContainsKey(serverPeer.ServerType))
            {
                Logger.ErrorFormat("Server {0} already registered with {1}", peerType, serverPeer.ServerType);
                return false;
            }

            _serverPeers.Add(peerType, serverPeer);

            Logger.InfoFormat("Registered server {0} with server {1}", peerType, serverPeer.ServerType);

            return true;
        }

        public bool UnregisterServerPeer(ServerTypes peerType, IServerPeer serverPeer)
        {
            if (!_serverPeers.ContainsKey(serverPeer.ServerType)) return false;

            _serverPeers.Remove(serverPeer.ServerType);
            return false;
        }

        public Dictionary<ServerTypes, IServerPeer> GetServerPeers()
        {
            return _serverPeers;
        }

        public IServerPeer GetServerPeerByType(ServerTypes serverType)
        {
            return _serverPeers.FirstOrDefault(c => c.Key == serverType).Value;
        }
    }
}
